package cn.cloudplug.friendsrecommend.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;


import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;


public class HttpTast extends AsyncTask<String, Void, JSONObject>{
	
	private Activity activity;
	public HttpTast(Activity activity){
		this.activity=activity;
	}
	@Override
	protected JSONObject doInBackground(String... params) {
		try {
			/* 建立HTTP Post连线 */
			HttpPost httpRequest = new HttpPost(params[0]);
			// Post运作传送变数必须用NameValuePair[]阵列储存
			// 传参数 服务端获取的方法为request.getParameter("name")
			List<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("cmd", params[1]));
			param.add(new BasicNameValuePair("username", params[2]));
			param.add(new BasicNameValuePair("password",params[3]));
			// 发出HTTP request
			httpRequest.setEntity(new UrlEncodedFormEntity(param,
					HTTP.UTF_8));
			// 取得HTTP response
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequest);

			// 若状态码为200 ok
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 取出回应字串
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				JSONObject json = new JSONObject(strResult);
				return json;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
